//
//  TalkfunQuestionNumberCard.swift
//  test
//
//  Created by 莫瑞权 on 2021/12/9.
//

import UIKit

class TalkfunQuestionNumberCard: UIView ,UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout {
    
    // 随堂考  表单
    var type:TFExaminationType = TFExaminationTypeTestPaper
    //关闭或返回
    let back:TalkfunIncreaseButton = TalkfunIncreaseButton.init()
    //题号卡
    let label:UILabel = UILabel.init()
    //标题
    let title:UILabel = UILabel.init()
    
    let list:NSMutableArray = NSMutableArray.init()
    var didSelectBlock: dellDidSelectBlock?
    //列表
    var collectionView:UICollectionView?
    let TalkfunQuestionNumberCardCell_ID = "TalkfunQuestionNumberCardCell"
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
 
        self.addSubview(self.back)
        self.back.layer.cornerRadius = 2;
        self.back.backgroundColor = UIColor.clear
        self.back.addTarget(self, action: #selector(self.backClick), for: UIControl.Event.touchUpInside)
        self.back.setImage(UIImage.init(named: "HTLive.bundle/TFreturn"), for: UIControl.State.normal)
        
     
        let attrString = NSMutableAttributedString(string: "题号卡")
        self.label.numberOfLines = 0
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang SC", size: 18)as Any,.foregroundColor: UIColor(red: 0.08, green: 0.09, blue: 0.1,alpha:1), ]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        self.label.attributedText = attrString
        self.addSubview(self.label)
       
    
        let titleAttrString = NSMutableAttributedString(string: "点击题号可跳转到对应的题目")
        self.title.numberOfLines = 0
        let titleAttr: [NSAttributedString.Key : Any] = [.font: UIFont(name: "PingFang SC", size: 14)as Any,.foregroundColor: UIColor(red: 0.59, green: 0.63, blue: 0.67,alpha:1), ]
        titleAttrString.addAttributes(titleAttr, range: NSRange(location: 0, length: titleAttrString.length))
        self.title.attributedText = titleAttrString
        self.title.textAlignment = NSTextAlignment.center
        self.addSubview(self.title)
        
        
        let layout = UICollectionViewFlowLayout();
            layout.minimumLineSpacing = 13
        let collectionViewW = self.frame.size.width
        let collectionViewH = self.frame.size.height  - 54.0
        let collectionViewFrame = CGRect(x: 0, y: 54.0, width: collectionViewW , height: collectionViewH)
        self.collectionView = UICollectionView.init(frame: collectionViewFrame, collectionViewLayout: layout)
        self.addSubview(self.collectionView!)
        self.collectionView?.dataSource = self
        self.collectionView?.delegate = self
        self.collectionView?.register(TalkfunQuestionNumberCardCell.self, forCellWithReuseIdentifier:TalkfunQuestionNumberCardCell_ID)
        
        self.collectionView?.backgroundColor = UIColor.clear
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let closeOrBackY = 15.0
        let closeOrBackW = 15.0
        let closeOrBackX = self.frame.width - 15.0 - 15.0
        let closeOrBackH = 15.0
        self.back.frame = CGRect(x: closeOrBackX, y: closeOrBackY, width: closeOrBackW, height: closeOrBackH)
        
        self.label.frame = CGRect(x: 15, y: 22.5, width: 54, height: 25)
        
        self.title.frame = CGRect(x: 0, y: 27.5, width: self.frame.width, height: 20)
        
        let collectionViewW = self.frame.size.width
        let collectionViewH = self.frame.size.height  - 65.5
        let collectionViewFrame = CGRect(x: 0, y: 65.5, width: collectionViewW , height: collectionViewH)
        self.collectionView?.frame = collectionViewFrame
    }
    
    @objc public func addData(list:NSArray,type:TFExaminationType)
    {
        self.list.removeAllObjects()
        
        self.type = type;
        
        //添加题目列表
        for i in stride(from: 0, to: list.count ,by: 1) {
            
            let examineDetail = list[i] as! TalkfunSubjectExamineDetail
            
            let aa = TalkfunQuestionNumberModel.init()
            
           //已经答
            if(examineDetail.subjectExamineAnswerDetailInfo.answer.count > 0 )
            {
                let str = examineDetail.subjectExamineAnswerDetailInfo.answer[0] as! NSString
                
                if str.length > 0 {
                    aa.selected = true
                }
                
                
            }
            
            //显示第几题专用
            aa.number = i + 1
            aa.isRequired = examineDetail.subjectInfo.isRequired
            if aa.isRequired {
//                print("必选========>")
            }
            self.list.add(aa)
        }
        self.collectionView?.reloadData()
    }
    
    @objc func selectedNumberCard(inx:NSInteger ,state:Bool)
    {
        
        if( inx < self.list.count)
        {
            let num = self.list[inx] as! TalkfunQuestionNumberModel
            
            num.selected = state

            self.collectionView?.reloadData()
        }
        
    }
        
    
    
    //是否填写好所有题目
    @objc func isCompleteTheAnswer()->Bool
    {
        var isSelectedCount = 0
        for num in self.list {
             let model = num as! TalkfunQuestionNumberModel
            
            if(model.selected)
            {
                isSelectedCount = isSelectedCount + 1
            }
            
        }
        if(isSelectedCount == self.list.count)
        {
            return true
        }
        
        return false
        
    }
    @objc func isListRequired()->Bool
    {
        var isRequiredCount = 0 //必答题 总数
        var isSelectedCount = 0 //已填写的必答题
      
       
        for num in self.list {
            
             let model = num as! TalkfunQuestionNumberModel
            
            //必答题
            if(model.isRequired == true  )
            {
                isRequiredCount = isRequiredCount + 1
//                print("必选========>")
                if model.selected {
                    isSelectedCount = isSelectedCount + 1
                    
//                    print("已选========>")
                }
                
            }
            
        }
        if(isSelectedCount == isRequiredCount)
        {
            return true
        }
        
        return false
        
    }
    
   @objc func backClick(btn:UIButton)
    {
        self.animate()
    }
    
    func animate()
    {
        UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
            self.frame = CGRect(x: 0.0, y: self.frame.size.height, width: self.frame.size.width, height: self.frame.size.height)
        } completion: { Bool in
            
        }
    }
    //TODO: 数据源
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.list.count
    }
    //TODO: cell的创建
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: TalkfunQuestionNumberCardCell_ID, for: indexPath) as! TalkfunQuestionNumberCardCell
      
        let model = self.list[indexPath.row] as! TalkfunQuestionNumberModel
        //超出主层边框的都会被裁减调用
        cell.layer.masksToBounds  =  true;
        let str = NSString(format: "%li", model.number)
        cell.textLabel.text = str as String
        // 圆角半径  能把一个下正文体,改成圆形
        cell.layer.cornerRadius = 45.0/2.0;
        //true
     
        if (model.selected)
        {
            cell.backgroundColor = UIColor(red: 0.25, green: 0.59, blue: 0.92, alpha: 0.1)
            cell.textLabel.textColor = UIColor(red: 0.25, green: 0.59, blue: 0.92,alpha:0.92)
        }else{
            cell.backgroundColor = UIColor(red: 0.96, green: 0.96, blue: 0.97, alpha: 1)
            cell.textLabel.textColor = UIColor(red: 0.08, green: 0.09, blue: 0.1,alpha:1)
        }
       
        cell.textLabel.font = UIFont(name: "PingFang SC", size: 20)
        
        return cell
    }
    //TODO: UICollectionViewCell高度
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 45.0, height: 45.0)
    }
    // cell与上下间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 13
    }
   //  ell与左右间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 13
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 0, left: 20, bottom: 0, right: 20)
    }
    //TODO: 點選 cell 後執行的動作
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        if self.didSelectBlock != nil {
            self.didSelectBlock!(indexPath.row)
        }
        print("第 \(indexPath.item ) 个题号卡")
        self.animate()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class TalkfunQuestionNumberModel: NSObject
{
    var number:NSInteger = 0
    
    var selected:Bool = false
    //必答题
    var isRequired:Bool = false
}
